/**
 * @Author your name
 * @Date 2021-03-04 15:22:56
 * @LastEditTime 2021-03-05 17:27:46
 * @LastEditors Please set LastEditors
 * @Description In User Settings Edit
 * @FilePath \fed-e-task-04-06\code\angular-demo\src\app\app.component.ts
 */
import { animate, AnimationEvent, group, keyframes, query, style, transition, trigger } from '@angular/animations';
import { HttpClient, HttpHeaderResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { AfterViewChecked, AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { fromEvent, Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { collapsedExpanded, slideAnimation, todoAniamtions } from './animation';
import { AppState } from './store';
import { async_increment, decrement, increment } from './store/actions/counter.actions';
import { addTodo, deleteTodo } from './store/actions/todo.actions';
import { counteFeatureKey } from './store/reducers/counter.reducer';
import { Todo } from './store/reducers/todo.reducer';
import { selectCount } from './store/selectors/counter.selectors';
import { selectCurrentRoute } from './store/selectors/router.selectors';
import { selectTodos } from './store/selectors/todo.selectors';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [`
    .routerContainer {
      position: relative;
    }
   
    .routerContainer > * {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
    }
  `],
  // 定义动画
  animations: [ 
    slideAnimation, 
    todoAniamtions, 
    collapsedExpanded,
    trigger("routerAnimation", [
      transition("one => two, one => three, two => three", [
        query(":enter", style({ transform: "translateX(100%)", opacity: 0 })),
        group([
          query(":enter", animate("10s ease-in", style({ transform: "translateX(0)", opacity: 1 }) )),
          query(":leave", animate("10s ease-out", style({ transform: "translateX(-100%)", opacity: 0 }) )),
        ])
      ]),
      transition("three => two, three => one, two => one", [
        query(":enter", style({ transform: "translateX(-100%)", opacity: 0 })),
        group([
          query(":enter", animate("10s ease-in", style({ transform: "translateX(0)", opacity: 1 }) )),
          query(":leave", animate("10s ease-out", style({ transform: "translateX(100%)", opacity: 0 }) )),
        ])
      ]),
    ])
  ]
})
export class AppComponent implements AfterViewInit {
  collapsed = false
  @ViewChild('AddTodoInput') AddTodoInput!: ElementRef
  
  todos: Observable<Todo[]>
  
  constructor (private store: Store<AppState>) {
    this.todos = this.store.pipe(select(selectTodos))
    this.store.pipe(select(selectCurrentRoute)).subscribe(console.log)
  }

  ngAfterViewInit () {
    fromEvent<KeyboardEvent>(this.AddTodoInput.nativeElement, 'keyup')
      .pipe(
        // 筛选出 Enter 键盘抬起事件的数据流
        filter(event => event.key ==="Enter"),
        // 拿到输入框的内容
        map(event => (<HTMLInputElement>event.target).value),
        // 去除首尾空格
        map(title => title.trim()),
        // 筛选出 title 不为空的数据流
        filter(title => title !== '')
      )
      .subscribe(title => {
        // 触发 dispatch
        this.store.dispatch(addTodo({ title }))
        // 清空输入框
        this.AddTodoInput.nativeElement.value = ''
      })
  }

  deleteTodo (id: string) {
    this.store.dispatch(deleteTodo({ id }))
  }

  startSlide (event: AnimationEvent) {
    console.log('startSlide', event)
  }

  doneSlide (event: AnimationEvent) {
    console.log('doneSlide', event)
  }

  toggle () {
    this.collapsed = !this.collapsed
  }

  prepare (outlet: RouterOutlet) {
    if (
      outlet && 
      outlet.activatedRouteData && 
      outlet.activatedRouteData.animation
    ) {
      console.log(outlet.activatedRouteData.animation)
      return outlet.activatedRouteData.animation
    }
  }
}
// export class AppComponent implements OnInit {
//   count: Observable<number>
//   constructor (private store: Store<AppState>) {
//     this.count = this.store.pipe(select(selectCount))
//   }

//   ngOnInit () {
//   }

//   increment () {
//     this.store.dispatch(increment({ count: 5}))
//   }

//   async_increment () {
//     this.store.dispatch(async_increment())
//   }

//   decrement () {
//     this.store.dispatch(decrement())
//   }
// }
// export class AppComponent implements OnInit {
//   constructor (private http: HttpClient) {}

//   ngOnInit () {
//     // let params = new HttpParams({ 
//     //   // fromObject: { name: 'zhangsan', age: '20' },
//     //   fromString: 'name=zhangsan&age=20'
//     // })
    
//     // // 需要对 params 重新赋值，否则不会生效
//     // params = params.append('sex', 'female')

//     // let headers = new HttpHeaders({ test: 'Hello'})

//     // this.http
//     //   .get('https://jsonplaceholder.typicode.com/users', { 
//     //     observe: 'response' 
//     //   })
//     //   .subscribe(console.log)
//     // this.http.get("/api/hello").subscribe(console.log)
//   }
// }